<template>
  <div class="app-container" v-loading="loading">
    <!-- 头部信息 -->
    <div class="route-header">
      <div class="route-title">
        <h2>{{ routeInfo.name }} <span class="route-code">{{ routeInfo.code }}</span></h2>
      </div>
      <div class="route-meta">
        <div class="meta-item">
          <span class="label">创建人：</span>
          <span class="value">{{ routeInfo.create_by }}</span>
        </div>
        <div class="meta-item">
          <span class="label">创建时间：</span>
          <span class="value">{{ routeInfo.create_time }}</span>
        </div>
        <div class="meta-item">
          <span class="label">更新人：</span>
          <span class="value">{{ routeInfo.update_by }}</span>
        </div>
        <div class="meta-item">
          <span class="label">更新时间：</span>
          <span class="value">{{ routeInfo.update_time }}</span>
        </div>
      </div>
      
      <!-- 删除操作按钮区域 -->
    </div>

    <!-- 标签页 -->
    <el-tabs v-model="activeTab" type="card">
      <!-- 基础信息标签页 -->
      <el-tab-pane label="基础信息" name="basic">
        <div class="info-container">
          <el-form label-width="120px" class="info-form">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="工艺路线编号">
                  <span>{{ routeInfo.code }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="工艺路线名称">
                  <span>{{ routeInfo.name }}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="状态">
                  <el-tag :type="routeInfo.status === '启用' ? 'success' : 'info'">
                    {{ routeInfo.status }}
                  </el-tag>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="说明">
                  <span>{{ routeInfo.description }}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="备注">
                  <span>{{ routeInfo.remark }}</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-tab-pane>
      
      <!-- 工序组成标签页 -->
      <el-tab-pane label="工序组成" name="process">
        <div class="process-container" v-loading="processLoading">
          <!-- 工序流程图 -->
          <div class="process-flow">
            <div 
              v-for="(process, index) in processList" 
              :key="index"
              class="process-step"
              :class="{ active: currentProcessIndex === index }"
              @click="selectProcess(index)"
            >
              <div class="step-content">
                <div class="step-index">{{ index + 1 }}</div>
                <div class="step-name">{{ process.name }}</div>
              </div>
              <div v-if="index < processList.length - 1" class="step-arrow">
                <i class="el-icon-arrow-right"></i>
              </div>
            </div>
          </div>
          
          <!-- 当前工序的物料清单 -->
          <div class="process-materials" v-if="processList.length > 0" v-loading="materialLoading">
            <div class="material-header">
              <h3>{{ processList[currentProcessIndex] ? processList[currentProcessIndex].name : '' }} - 物料清单</h3>
            </div>
            <el-table :data="currentMaterials" border stripe>
              <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
              <el-table-column prop="material_code" label="物料编号" min-width="120"></el-table-column>
              <el-table-column prop="material_name" label="物料名称" min-width="150"></el-table-column>
              <el-table-column prop="material_sfn" label="规格型号" min-width="120"></el-table-column>
              <el-table-column prop="material_unit" label="单位" width="80" align="center"></el-table-column>
              <el-table-column prop="usage_num" label="使用量" width="100" align="center"></el-table-column>
              <el-table-column prop="remarks" label="备注" min-width="120"></el-table-column>
            </el-table>
          </div>
        </div>
      </el-tab-pane>
      
      <!-- 关联产品标签页 -->
      <el-tab-pane label="关联产品" name="product">
        <div class="product-container" v-loading="productLoading">
          <el-table :data="relatedProducts" border stripe>
            <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
            <el-table-column prop="product_code" label="产品编号" min-width="120"></el-table-column>
            <el-table-column prop="product_name" label="产品名称" min-width="150"></el-table-column>
            <el-table-column prop="product_sfn" label="规格型号" min-width="120"></el-table-column>
            <el-table-column prop="product_unit" label="单位" width="80" align="center"></el-table-column>
            <el-table-column prop="product_type" label="产品类别" min-width="120">
              <template slot-scope="scope">
                {{ formatProductType(scope.row.product_type) }}
              </template>
            </el-table-column>
            <el-table-column prop="remarks" label="备注" min-width="120"></el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { getRoute, listop1, listop2, listop3 } from "@/api/sc/operational";
import { getProcessDetail, getme } from "@/api/sc/process";

export default {
  name: "ProcessRouteDetail",
  data() {
    return {
      routeId: null,
      activeTab: "basic",
      currentProcessIndex: 0,
      loading: false,
      processLoading: false, // 工序加载状态
      materialLoading: false, // 物料加载状态
      routeInfo: {
        id: "",
        code: "",
        name: "",
        status: "启用",
        description: "",
        remark: "",
        create_by: "",
        create_time: "",
        update_by: "",
        update_time: ""
      },
      processList: [],
      materialsList: [],
      relatedProducts: [],
      productLoading: false // 产品加载状态
    };
  },
  computed: {
    currentMaterials() {
      if (this.processList.length === 0) return [];
      
      const currentProcess = this.processList[this.currentProcessIndex];
      return this.materialsList.filter(material => 
        material.process_id === currentProcess.id
      );
    }
  },
  watch: {
    activeTab(newVal) {
      if (newVal === 'process') {
        this.getProcessDetails();
      } else if (newVal === 'product') {
        this.getRelatedProducts();
      }
    }
  },
  created() {
    this.routeId = this.$route.params.id;
    this.getRouteDetail();
    
    // 如果初始标签页是工序组成，则立即加载工序数据
    if (this.activeTab === 'process') {
      this.getProcessDetails();
    }
  },
  methods: {
    // 获取工艺路线详情
    getRouteDetail() {
      // 从sessionStorage获取数据
      const routeDetailDataStr = sessionStorage.getItem('routeDetailData');
      
      // 如果有缓存数据，直接使用
      if (routeDetailDataStr) {
        try {
          const routeDetailData = JSON.parse(routeDetailDataStr);
          console.log("从sessionStorage获取的工艺路线详情:", routeDetailData);
          
          // 使用统一的数据处理方法
          this.processListop1Data(routeDetailData);
          
          // 清除sessionStorage中的数据，避免影响下一次访问
          sessionStorage.removeItem('routeDetailData');
          return;
        } catch (error) {
          console.error("解析sessionStorage中的数据失败:", error);
        }
      }
      
      // 如果没有缓存数据或解析失败，则直接调用API获取
      this.loading = true;
      listop1(this.routeId).then(response => {
        this.loading = false;
        if (response.data) {
          const routeDetailData = response.data;
          this.processListop1Data(routeDetailData);
        }
      }).catch(error => {
        this.loading = false;
        console.error("获取工艺路线详情失败:", error);
        this.$message.error("获取工艺路线详情失败");
        
        // 如果API调用失败，使用路由参数中的基本信息
        this.routeInfo = {
          id: this.routeId,
          code: this.$route.query.code || "",
          name: this.$route.query.name || "",
          status: "未知",
          description: "",
          remark: "",
          create_by: "",
          create_time: "",
          update_by: "",
          update_time: ""
        };
      });
    },
    
    // 统一处理listop1返回的数据
    processListop1Data(routeDetailData) {
      console.log("处理工艺路线数据:", routeDetailData);
      
      // 处理工艺路线基本信息
      this.routeInfo = {
        id: routeDetailData.operational_id || this.routeId,
        code: routeDetailData.operational_code || "",
        name: routeDetailData.operational_name || "",
        status: routeDetailData.operational_status == 1 ? "启用" : "停用",
        description: routeDetailData.operational_description || "",
        remark: routeDetailData.remarks || "",
        create_by: routeDetailData.create_by || "",
        create_time: routeDetailData.create_time || "",
        update_by: routeDetailData.update_by || "",
        update_time: routeDetailData.update_time || ""
      };
      
      // 处理工序列表
      if (routeDetailData.opdetailsList && routeDetailData.opdetailsList.length > 0) {
        // 按顺序排序工序
        const sortedProcesses = [...routeDetailData.opdetailsList].sort((a, b) => {
          return (a.sequence || 0) - (b.sequence || 0);
        });
        
        this.processList = sortedProcesses.map(process => ({
          id: process.process_id,
          name: process.process_name || "",
          order: process.sequence || 0,
          code: process.process_code || ""
        }));
      }
      
      // 处理物料清单
      if (routeDetailData.opdetailsList) {
        const materialList = [];
        routeDetailData.opdetailsList.forEach(process => {
          if (process.materials && process.materials.length > 0) {
            process.materials.forEach(material => {
              materialList.push({
                process_id: process.process_id,
                code: material.material_code || material.materialCode || "",
                name: material.material_name || material.materialName || "",
                specification: material.specification || "",
                unit: material.unit || "",
                quantity: material.quantity || 0,
                ratio: material.proportion ? material.proportion + "%" : "",
                remark: material.remark || ""
              });
            });
          }
        });
        this.materialsList = materialList;
      }
      
      // 处理关联产品
      if (routeDetailData.products && routeDetailData.products.length > 0) {
        this.relatedProducts = routeDetailData.products.map(product => ({
          code: product.product_code || "",
          name: product.product_name || "",
          specification: product.specification || "",
          unit: product.unit || "",
          category: product.category_name || "",
          remark: product.remark || ""
        }));
      }
    },
    
    // 选择工序
    selectProcess(index) {
      this.currentProcessIndex = index;
      
      // 获取选中工序的ID
      const selectedProcess = this.processList[index];
      console.log("选中工序:", selectedProcess);
      
      if (selectedProcess && selectedProcess.id) {
        console.log("开始获取工序物料, 工序ID:", selectedProcess.id);
        this.getProcessMaterials(selectedProcess.id);
      } else {
        console.error("工序ID不存在:", selectedProcess);
      }
    },
    
    // 获取工序物料详情
    getProcessMaterials(processId) {
      // 显示加载状态
      this.materialLoading = true;
      
      // 调用API获取工序物料详情
      getme(processId).then(response => {
        this.materialLoading = false;
        console.log("获取工序物料详情原始数据:", response);
          
          // 更新当前工序的物料列表
          const currentProcessId = this.processList[this.currentProcessIndex].id;
          
          // 移除之前该工序的物料
          this.materialsList = this.materialsList.filter(material => material.process_id !== currentProcessId);
          
        // 检查响应格式并正确获取数据
        if (response && response.code === 200) {
          // 处理标准响应格式：{code: 200, msg: '查询成功', rows: [...], total: n}
          let materials = [];
          
          if (response.rows && Array.isArray(response.rows)) {
            materials = response.rows;
          } else if (response.data && response.data.rows && Array.isArray(response.data.rows)) {
            materials = response.data.rows;
          } else if (response.data && Array.isArray(response.data)) {
            materials = response.data;
          }
          
          console.log("处理后的物料数据:", materials);
                
          if (materials && materials.length > 0) {
            // 添加新获取的物料，保留原始字段名
            materials.forEach(material => {
              // 添加处理后的物料，保持原始字段名
              const materialItem = {
                    process_id: currentProcessId,
                ...material
              };
              
              // 确保百分比格式
              if (materialItem.material_Ingredient_ratio && !String(materialItem.material_Ingredient_ratio).includes('%')) {
                materialItem.material_Ingredient_ratio = materialItem.material_Ingredient_ratio + '%';
            }
              
              this.materialsList.push(materialItem);
            });
          } else {
            console.warn("物料数据为空");
          }
        } else {
          console.warn("API返回格式异常或失败:", response);
        }
        
        console.log("最终物料列表:", this.materialsList.filter(m => m.process_id === currentProcessId));
      }).catch(error => {
        this.materialLoading = false;
        console.error("获取工序物料详情失败:", error);
        this.$message.error("获取工序物料详情失败");
      });
    },
    
    // 编辑
    handleEdit() {
      this.$message.info("编辑功能待实现");
      // 实际项目中可以跳转到编辑页面
      // this.$router.push({ name: 'ProcessRouteEdit', params: { id: this.routeId } });
    },
    
    // 删除
    handleDelete() {
      this.$modal.confirm('确认删除该工艺路线吗？').then(() => {
        // 调用删除API
        // this.$api.deleteProcessRoute(this.routeId).then(() => {
        //   this.$message.success("删除成功");
        //   this.$router.back();
        // });
        this.$message.success("删除功能待实现");
      }).catch(() => {});
    },
    
    // 复制
    handleCopy() {
      this.$message.info("复制功能待实现");
    },
    
    // 导出
    handleExport() {
      this.$message.info("导出功能待实现");
    },
    
    // 获取工序组成详情
    getProcessDetails() {
      // 显示加载状态
      this.processLoading = true;
      
      // 调用API获取工序组成详情
      listop2(this.routeId).then(response => {
        this.processLoading = false;
        console.log("获取工序组成详情:", response);
        
        // 检查并处理不同的数据结构
        if (response.data) {
          console.log("工序数据结构:", response.data);
          
          // 处理数据为数组的情况
          if (Array.isArray(response.data)) {
            // 按顺序排序工序
            const sortedProcesses = [...response.data].sort((a, b) => {
              return (a.sequence || 0) - (b.sequence || 0);
            });
            
            // 更新工序列表
            this.processList = sortedProcesses.map(process => ({
              id: process.process_id,
              name: process.process_name || "",
              order: process.sequence || 0,
              code: process.process_code || ""
            }));
          } 
          // 处理包含rows数组的情况
          else if (response.data.rows && Array.isArray(response.data.rows)) {
            // 按顺序排序工序
            const sortedProcesses = [...response.data.rows].sort((a, b) => {
              return (a.sequence || 0) - (b.sequence || 0);
            });
            
            // 更新工序列表
            this.processList = sortedProcesses.map(process => ({
              id: process.process_id,
              name: process.process_name || "",
              order: process.sequence || 0,
              code: process.process_code || ""
            }));
          }
          
          // 处理物料清单
          const materialList = [];
          
          // 根据数据结构选择正确的数据源
          const processData = Array.isArray(response.data) ? response.data : 
                            (response.data.rows && Array.isArray(response.data.rows)) ? response.data.rows : [];
          
          processData.forEach(process => {
            if (process.materials && process.materials.length > 0) {
              process.materials.forEach(material => {
                materialList.push({
                  process_id: process.process_id,
                  material_code: material.material_code || "",
                  material_name: material.material_name || "",
                  material_sfn: material.material_sfn || "",
                  material_unit: material.material_unit || "",
                  usage_num: material.usage_num || 0,
                  remarks: material.remarks || ""
                });
              });
            }
          });
          this.materialsList = materialList;
          
          // 如果工序列表不为空，默认选中第一个工序并加载该工序的物料
          if (this.processList.length > 0) {
            this.currentProcessIndex = 0;
            
            // 自动加载第一个工序的物料
            const firstProcessId = this.processList[0].id;
            if (firstProcessId) {
              console.log("自动加载第一个工序的物料, 工序ID:", firstProcessId);
              this.getProcessMaterials(firstProcessId);
            }
          }
        }
      }).catch(error => {
        this.processLoading = false;
        console.error("获取工序组成详情失败:", error);
        this.$message.error("获取工序组成详情失败");
      });
    },

    // 获取关联产品
    getRelatedProducts() {
      this.productLoading = true;
      
      // 调用API获取关联产品
      listop3(this.routeId).then(response => {
        this.productLoading = false;
        console.log("获取关联产品详情:", response);
        
        if (response && response.code === 200) {
          // 处理标准响应格式
          let products = [];
          
          if (response.rows && Array.isArray(response.rows)) {
            products = response.rows;
          } else if (response.data && response.data.rows && Array.isArray(response.data.rows)) {
            products = response.data.rows;
          } else if (response.data && Array.isArray(response.data)) {
            products = response.data;
          }
          
          console.log("处理后的产品数据:", products);
          
          // 更新关联产品列表
          if (products.length > 0) {
            // 直接使用原始字段，不进行映射
            this.relatedProducts = products;
          } else {
            this.relatedProducts = [];
            console.warn("关联产品数据为空");
          }
        } else {
          console.warn("API返回格式异常或失败:", response);
        }
      }).catch(error => {
        this.productLoading = false;
        console.error("获取关联产品详情失败:", error);
        this.$message.error("获取关联产品详情失败");
      });
    },

    // 格式化产品类别
    formatProductType(type) {
      // Convert string to number for comparison
      const typeNum = parseInt(type);
      
      switch (typeNum) {
        case 1:
          return '成品';
        case 2:
          return '半成品';
        case 3:
          return '其他';
        default:
          return type;
      }
    }
  }
};
</script>

<style scoped>
.route-header {
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.route-title {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.route-code {
  font-size: 14px;
  color: #909399;
  margin-left: 15px;
  font-weight: normal;
}

.route-meta {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 15px;
}

.meta-item {
  margin-right: 30px;
  margin-bottom: 5px;
}

.label {
  color: #606266;
  font-weight: bold;
}

.route-actions {
  display: flex;
  gap: 10px;
}

.info-container, .process-container, .product-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
}

.info-form {
  max-width: 900px;
}

.process-flow {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-bottom: 20px;
  padding: 15px 0;
  overflow-x: auto;
}

.process-step {
  display: flex;
  align-items: center;
  cursor: pointer;
  margin-right: 5px;
  margin-bottom: 10px;
}

.step-content {
  display: flex;
  align-items: center;
  padding: 8px 15px;
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.process-step.active .step-content {
  background-color: #ecf5ff;
  border-color: #409EFF;
  color: #409EFF;
}

.step-index {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: #909399;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 10px;
  font-size: 14px;
}

.process-step.active .step-index {
  background-color: #409EFF;
}

.step-arrow {
  margin: 0 10px;
  color: #909399;
}

.material-header {
  margin-bottom: 15px;
}

.material-header h3 {
  font-size: 16px;
  margin: 0;
}

.empty-tip {
  padding: 30px 0;
  text-align: center;
}
</style> 